
from theconfig import *
import sys

class BaseCountReader:
    def __init__(self, index, leftBuffer=100, rightBuffer=5000):
        self.index = index
        self.buffer = None
        self.currChr = None
        self.currMinPos = None
        self.currMaxPos = None
        self.LEFT_BUFFER = leftBuffer
        self.RIGHT_BUFFER = rightBuffer

    def __getitem__(self, loc):
        (chr, pos) = loc
        if self.buffer == None or chr != self.currChr or pos < self.currMinPos or pos > self.currMaxPos:
            self.currChr = chr
            self.currMinPos = pos - self.LEFT_BUFFER
            self.currMaxPos = pos + self.RIGHT_BUFFER
            self.buffer = [None] * (self.currMaxPos - self.currMinPos + 1)
            for feature in self.index.getFeatures((chr, pos - self.LEFT_BUFFER, pos + self.RIGHT_BUFFER)):
                self.buffer[feature.spos - self.currMinPos] = feature
        return self.buffer[pos - self.currMinPos]

